package com.atguigu.flink.chapter07.timer;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.HashMap;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/8/14 9:49
 */
public class Flink03_Project {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        env
            .socketTextStream("hadoop162", 9999)
            .map(new MapFunction<String, WaterSensor>() {
                @Override
                public WaterSensor map(String value) throws Exception {
                    String[] data = value.split(",");
                    return new WaterSensor(data[0], Long.valueOf(data[1]) * 1000, Integer.valueOf(data[2]));
                }
            })
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((data, ts) -> data.getTs())
            )
            .keyBy(WaterSensor::getId)
            .process(new KeyedProcessFunction<String, WaterSensor, String>() {
            
                HashMap<String, Boolean> firstMap = new HashMap<String, Boolean>();
                HashMap<String, Integer> lastVcMap = new HashMap<String, Integer>();
                HashMap<String, Long> timerMap = new HashMap<String, Long>();
            
                @Override
                public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                    out.collect(ctx.getCurrentKey() + " 水位在5s内连续上升, 红色预警...");
                    // 删除这个sensor对应的第一次的状态
                    firstMap.remove(ctx.getCurrentKey());
                }
            
                @Override
                public void processElement(WaterSensor value,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    /*
                    1. 第一条数据进来, 注册定时器
                    2. 第二条数据进来, 与上个数据进行对比
                    3. 如果上升, 则什么都不做
                    4. 如果下降, 则删除定时器, 然后注册一个新的定时器
                    
                    5. 如果定时器触发了, 需要重新注册一个新的定时器
                     */
                    Boolean isFirst = firstMap.get(ctx.getCurrentKey());
                    if (isFirst == null) { // 这个sensor第一次进来
                        System.out.println(ctx.getCurrentKey() + " 第一次进来...");
                        firstMap.put(ctx.getCurrentKey(), false);
                        // 注册定时器
                        ctx.timerService().registerEventTimeTimer(value.getTs() + 5000);
                        timerMap.put(ctx.getCurrentKey(), value.getTs() + 5000);
                    
                    } else {
                        // 不是第一次
                        // 判断这次水位是否相比上次水位在上升
                        Integer lastVc = lastVcMap.get(ctx.getCurrentKey());
                        if (value.getVc() <= lastVc) { // 没有上升
                            System.out.println(ctx.getCurrentKey() + " 水位下降或者不变");
                        
                            // 删除定时器
                            ctx.timerService().deleteEventTimeTimer(timerMap.get(ctx.getCurrentKey()));
                            
                        } else {
                            System.out.println(ctx.getCurrentKey() + " 水位上升");
                        }
                    }
                
                    // 保存这次的水位值, 给下一次使用
                    lastVcMap.put(ctx.getCurrentKey(), value.getVc());
                
                }
            })
            .print();
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
